package com.nuedu.corejava.ch14;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.Scanner;


public class ChatClient {

	public void chat(String host, int port) {
		Socket socket = null;
		InputStream inputStream = null;
		OutputStream outputStream = null;
		Scanner scanner = null;

		try {
			//1.打开socket连接，连接服务器
			socket = new Socket(host, port);
			System.out.println("连接服务器成功!");
			//2.打开输入流
			inputStream = socket.getInputStream();
			outputStream = socket.getOutputStream();
			scanner = new Scanner(System.in);
			byte[] buffer = new byte[512];

			while (true) {
				//3.打开键盘，并输入聊天内容
				System.out.println("请输入(结束聊天输入quit)： ");
				String words = scanner.nextLine();
				//4.把聊天内容发送到服务器
				outputStream.write(words.getBytes());
				System.out.println("发送到服务器成功");
				//如果用户输入quit则需要退出聊天
				if ("quit".equalsIgnoreCase(words)) {
					break;
				}
				//5.读取服务器返回的数据，并显示
				int length = inputStream.read(buffer);
				String reply = new String(buffer, 0, length).trim();
				System.out.println(reply);
			}
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}finally {
			closeAll(socket, inputStream, outputStream, scanner);
		}

	}
	private void closeAll(Socket socket,InputStream inputStream,
			OutputStream outputStream,Scanner scanner) {
		if (scanner!=null) {
			scanner.close();
		}if (outputStream!=null) {
			try {
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}if (inputStream!=null) {
			try {
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}if (socket!=null) {
			try {
				socket.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	public static void main(String[] args) {
		String host = "192.168.1.41";
		int port = 8888;
		ChatClient chatClient = new ChatClient();
		chatClient.chat(host, port);
		
	}

}
